<?php
namespace app\controller;

use app\BaseController;
use app\model\Permission as PermissionModel;
use think\facade\Validate;
use think\facade\Db;

class Permission extends BaseController
{
    /**
     * 获取权限列表
     */
    public function index()
    {
        // 获取请求参数
        $params = $this->request->get();
        
        // 构建查询
        $query = PermissionModel::order('id', 'asc');
        
        // 按名称搜索
        if (!empty($params['name'])) {
            $query = $query->whereLike('name', '%' . $params['name'] . '%');
        }
        
        // 按代码搜索
        if (!empty($params['code'])) {
            $query = $query->whereLike('code', '%' . $params['code'] . '%');
        }
        
        // 按类型搜索
        if (isset($params['type']) && $params['type'] !== '') {
            $query = $query->where('type', $params['type']);
        }
        
        // 按父级ID搜索
        if (isset($params['parent_id']) && $params['parent_id'] !== '') {
            $query = $query->where('parent_id', $params['parent_id']);
        }
        
        // 按状态搜索
        if (isset($params['status']) && $params['status'] !== '') {
            $query = $query->where('status', $params['status']);
        }
        
        // 分页
        $list = $query->paginate([
            'list_rows' => $params['pageSize'] ?? 10,
            'page' => $params['page'] ?? 1,
        ]);
        
        return $this->success('获取成功', $list);
    }
    
    /**
     * 获取权限树形结构
     */
    public function tree()
    {
        // 获取请求参数
        $params = $this->request->get();
        
        // 构建查询
        $query = PermissionModel::order(['sort' => 'asc', 'id' => 'asc']);
        
        // 按名称搜索
        if (!empty($params['name'])) {
            $query = $query->whereLike('name', '%' . $params['name'] . '%');
        }
        
        // 按代码搜索
        if (!empty($params['code'])) {
            $query = $query->whereLike('code', '%' . $params['code'] . '%');
        }
        
        // 按类型搜索
        if (isset($params['type']) && $params['type'] !== '') {
            $query = $query->where('type', $params['type']);
        }
        
        // 按状态搜索
        if (isset($params['status']) && $params['status'] !== '') {
            $query = $query->where('status', $params['status']);
        }
        
        // 获取所有权限
        $list = $query->select();
        
        // 构建树形结构
        $tree = $this->buildTree($list->toArray());
        
        return $this->success('获取成功', $tree);
    }
    
    /**
     * 添加权限
     */
    public function add()
    {
        // 获取请求数据
        $data = $this->request->post();
        
        // 验证数据
        $validate = Validate::rule([
            'name' => 'require|max:50',
            'code' => 'require|alphaDash|unique:permission',
            'type' => 'require|in:menu,module,button',
            'parent_id' => 'number',
            'status' => 'require|in:0,1',
            'sort' => 'number',
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 验证父级ID
        if (!empty($data['parent_id'])) {
            $parent = PermissionModel::find($data['parent_id']);
            if (!$parent) {
                return $this->error('父级权限不存在');
            }
        }
        if($data['type'] == 'menu'){
            $data['type'] = 1;
        }
        if($data['type'] == 'button'){
            $data['type'] = 2;
        }
        if($data['type'] == 'module'){
            $data['type'] = 3;
        }
        // 创建权限
        try {
            $permission = PermissionModel::create([
                'name' => $data['name'],
                'code' => $data['code'],
                'type' => $data['type'],
                'parent_id' => $data['parent_id'] ?? 0,
                'status' => $data['status'],
                'sort' => $data['sort'] ?? 0,
            ]);
            
            return $this->success('添加成功', $permission);
            
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }
    
    /**
     * 编辑权限
     */
    public function edit()
    {
        // 获取请求数据
        $data = $this->request->put();
        
        // 验证数据
        $validate = Validate::rule([
            'id' => 'require|number',
            'name' => 'require|max:50',
            'code' => 'alphaDash',
            'type' => 'require|in:menu,module,button',
            'parent_id' => 'number',
            'status' => 'require|in:0,1',
            'sort' => 'number',
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 查询权限
        $permission = PermissionModel::find($data['id']);
        if (!$permission) {
            return $this->error('权限不存在');
        }
        
        // 如果修改了代码，需要检查唯一性
        if (isset($data['code']) && $data['code'] !== $permission->code) {
            if (PermissionModel::where('code', $data['code'])->where('id', '<>', $data['id'])->find()) {
                return $this->error('权限代码已存在');
            }
        }
        
        // 验证父级ID
        if (!empty($data['parent_id'])) {
            // 不能将自己或下级设为父级
            if ($data['parent_id'] == $data['id']) {
                return $this->error('不能将自己设为父级');
            }
            
            // 查找所有下级ID
            $childrenIds = $this->getChildrenIds($data['id']);
            if (in_array($data['parent_id'], $childrenIds)) {
                return $this->error('不能将下级设为父级');
            }
            
            // 查询父级是否存在
            $parent = PermissionModel::find($data['parent_id']);
            if (!$parent) {
                return $this->error('父级权限不存在');
            }
        }
        if($data['type'] == 'menu'){
            $data['type'] = 1;
         }
         if($data['type'] == 'button'){
            $data['type'] = 2;
         }
         if($data['type'] == 'module'){
            $data['type'] = 3;
         }
        
        // 更新权限
        try {
            $permission->save([
                'name' => $data['name'],
                'code' => $data['code'] ?? $permission->code,
                'type' => $data['type'],
                'parent_id' => $data['parent_id'] ?? 0,
                'status' => $data['status'],
                'sort' => $data['sort'] ?? 0,
            ]);
            
            return $this->success('更新成功');
            
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }
    
    /**
     * 删除权限
     * @param int $id 权限ID
     */
    public function delete($id)
    {
        // 验证参数
        if (!$id || !is_numeric($id)) {
            return $this->error('参数错误');
        }
        
        // 查询权限
        $permission = PermissionModel::find($id);
        if (!$permission) {
            return $this->error('权限不存在');
        }
        
        // 检查是否有子权限
        $childCount = PermissionModel::where('parent_id', $id)->count();
        if ($childCount > 0) {
            return $this->error('该权限下有子权限，不能删除');
        }
        
        // 检查权限是否被角色使用
        $roleCount = $permission->roles()->count();
        if ($roleCount > 0) {
            return $this->error('该权限已被角色使用，不能删除');
        }
        
        // 删除权限
        try {
            $permission->delete();
            return $this->success('删除成功');
            
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取权限详情
     * @param int $id 权限ID
     */
    public function detail($id)
    {
        $id = $this->request->get('id');

        // 验证参数
        if (!$id || !is_numeric($id)) {
            return $this->error('参数错误');
        }
        
        // 查询权限
        $permission = PermissionModel::find($id);
        if (!$permission) {
            return $this->error('权限不存在');
        }
        
        return $this->success('获取成功', $permission);
    }
    
    /**
     * 构建权限树形结构
     * @param array $permissions 权限列表
     * @param int $parentId 父级ID
     * @return array 树形结构
     */
    private function buildTree($permissions, $parentId = 0)
    {
        $tree = [];
        
        foreach ($permissions as $permission) {
            if ($permission['parent_id'] == $parentId) {
                $children = $this->buildTree($permissions, $permission['id']);
                if (!empty($children)) {
                    $permission['children'] = $children;
                }
                $tree[] = $permission;
            }
        }
        
        return $tree;
    }
    
    /**
     * 获取权限的所有下级ID
     * @param int $id 权限ID
     * @return array 下级ID数组
     */
    private function getChildrenIds($id)
    {
        $childrenIds = [];
        
        $children = PermissionModel::where('parent_id', $id)->column('id');
        $childrenIds = array_merge($childrenIds, $children);
        
        foreach ($children as $childId) {
            $childrenIds = array_merge($childrenIds, $this->getChildrenIds($childId));
        }
        
        return $childrenIds;
    }
} 